import axios from 'axios'
import store from '@/store'

// Create axios instance with base URL
const api = axios.create({
  baseURL: 'http://localhost:8080',
  withCredentials: true // 允许跨域请求携带凭证
})

// 创建一个公开的API实例，不需要认证就可访问
export const publicApi = axios.create({
  baseURL: 'http://localhost:8080',
  withCredentials: true
})

// 为公开API添加请求/响应拦截器（仅用于日志记录，不添加认证）
publicApi.interceptors.request.use(
  config => {
    console.log(`Public API Request: ${config.method.toUpperCase()} ${config.url}`, config);
    return config;
  },
  error => Promise.reject(error)
)

publicApi.interceptors.response.use(
  response => {
    console.log(`Public API Response: ${response.status} ${response.config.url}`, response.data);
    return response;
  },
  error => {
    console.error(`Public API Error: ${error.config?.url || 'unknown URL'}`, error);
    return Promise.reject(error);
  }
)

// Add request interceptor for auth token
api.interceptors.request.use(
  config => {
    // Add token to headers if available
    const token = store.getters['auth/token'] || store.state.token || localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 输出请求信息以便调试
    console.log(`API Request: ${config.method.toUpperCase()} ${config.url}`, config);
    
    return config
  },
  error => Promise.reject(error)
)

// Add response interceptor for error handling
api.interceptors.response.use(
  response => {
    // 输出响应信息以便调试
    console.log(`API Response: ${response.status} ${response.config.url}`, response.data);
    return response;
  },
  error => {
    // 输出错误信息以便调试
    console.error(`API Error: ${error.config?.url || 'unknown URL'}`, error);
    
    // Handle session expiration or unauthorized access
    if (error.response) {
      // 处理401未授权
      if (error.response.status === 401) {
        store.dispatch('auth/logout')
        // Redirect to login if not already there
        if (window.location.pathname !== '/login') {
          window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname)
        }
      }
      // 处理403禁止访问
      else if (error.response.status === 403) {
        console.error('权限不足，拒绝访问')
        // 可以在这里添加提示或重定向
      }
    }
    return Promise.reject(error)
  }
)

export default api 